package me.mysearch;

public class BinarySearchBalance {
    public static void main(String[] args) {
        int[] arr = {1, 5, 6, 7, 8, 9};
        int result = binarySearchBalance(arr, 8);
        System.out.println(result);
    }

    //平衡版
    //if else比较次数平衡
    //适用于数据量比较大时
    //在循环外比较
    public static int binarySearchBalance(int[] arr, int target) {
        //j只作为边界，不参与比较
        int i = 0, j = arr.length;
        while (1 < j - i) {
            int m = (i + j) >>> 1;
            if (target < arr[m]) {
                j = m;

            } else {
                i = m;
            }
        }
        /*if (arr[i] == target) {
            return i;
        } else {
            return -1;
        }*/
        return (arr[i] == target) ? i : -1;
    }
}
